package com.yss.common.core.utils.file;

import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.ArrayUtils;
import com.yss.common.core.utils.StringUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件处理工具类
 */
@Slf4j
public class FileUtils {
    /**
     * 字符常量：斜杠 {@code '/'}
     */
    public static final char SLASH = '/';

    /**
     * 字符常量：反斜杠 {@code '\\'}
     */
    public static final char BACKSLASH = '\\';

    public static String FILENAME_PATTERN = "[a-zA-Z0-9_\\-\\|\\.\\u4e00-\\u9fa5]+";

    /**
     * 输出指定文件的byte数组
     *
     * @param filePath 文件路径
     * @param os       输出流
     * @return
     */
    public static void writeBytes(String filePath, OutputStream os) throws IOException {
        FileInputStream fis = null;
        try {
            File file = new File(filePath);
            if (!file.exists()) {
                throw new FileNotFoundException(filePath);
            }
            fis = new FileInputStream(file);
            byte[] b = new byte[1024];
            int length;
            while ((length = fis.read(b)) > 0) {
                os.write(b, 0, length);
            }
        } catch (IOException e) {
            throw e;
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e1) {
                    log.error(e1.getMessage());
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e1) {
                    log.error(e1.getMessage());
                }
            }
        }
    }

    /**
     * 删除文件
     *
     * @param filePath 文件
     * @return
     */
    public static boolean deleteFile(String filePath) {
        boolean flag = false;
        File file = new File(filePath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists()) {
            flag = file.delete();
        }
        return flag;
    }

    /**
     * 文件名称验证
     *
     * @param filename 文件名称
     * @return true 正常 false 非法
     */
    public static boolean isValidFilename(String filename) {
        return filename.matches(FILENAME_PATTERN);
    }

    /**
     * 检查文件是否可下载
     *
     * @param resource 需要下载的文件
     * @return true 正常 false 非法
     */
    public static boolean checkAllowDownload(String resource) {
        // 禁止目录上跳级别
        if (StringUtils.contains(resource, "..")) {
            return false;
        }

        // 检查允许下载的文件规则
        if (ArrayUtils.contains(MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION, FileTypeUtils.getFileType(resource))) {
            return true;
        }

        // 不在允许下载的文件规则
        return false;
    }

    /**
     * 下载文件名重新编码
     *
     * @param request  请求对象
     * @param fileName 文件名
     * @return 编码后的文件名
     */
    public static String setFileDownloadHeader(HttpServletRequest request, String fileName) throws UnsupportedEncodingException {
        final String agent = request.getHeader("USER-AGENT");
        String filename = fileName;
        if (agent.contains("MSIE")) {
            // IE浏览器
            filename = URLEncoder.encode(filename, "utf-8");
            filename = filename.replace("+", " ");
        } else if (agent.contains("Firefox")) {
            // 火狐浏览器
            filename = new String(fileName.getBytes(), "ISO8859-1");
        } else if (agent.contains("Chrome")) {
            // google浏览器
            filename = URLEncoder.encode(filename, "utf-8");
        } else {
            // 其它浏览器
            filename = URLEncoder.encode(filename, "utf-8");
        }
        return filename;
    }

    /**
     * 返回文件名
     *
     * @param filePath 文件
     * @return 文件名
     */
    public static String getName(String filePath) {
        if (null == filePath) {
            return null;
        }
        int len = filePath.length();
        if (0 == len) {
            return filePath;
        }
        if (isFileSeparator(filePath.charAt(len - 1))) {
            // 以分隔符结尾的去掉结尾分隔符
            len--;
        }

        int begin = 0;
        char c;
        for (int i = len - 1; i > -1; i--) {
            c = filePath.charAt(i);
            if (isFileSeparator(c)) {
                // 查找最后一个路径分隔符（/或者\）
                begin = i + 1;
                break;
            }
        }

        return filePath.substring(begin, len);
    }

    /**
     * 是否为Windows或者Linux（Unix）文件分隔符<br>
     * Windows平台下分隔符为\，Linux（Unix）为/
     *
     * @param c 字符
     * @return 是否为Windows或者Linux（Unix）文件分隔符
     */
    public static boolean isFileSeparator(char c) {
        return SLASH == c || BACKSLASH == c;
    }

    /**
     * 下载文件名重新编码
     *
     * @param response     响应对象
     * @param realFileName 真实文件名
     * @return
     */
    public static void setAttachmentResponseHeader(HttpServletResponse response, String realFileName) throws UnsupportedEncodingException {
        String percentEncodedFileName = percentEncode(realFileName);

        StringBuilder contentDispositionValue = new StringBuilder();
        contentDispositionValue.append("attachment; filename=")
                .append(percentEncodedFileName)
                .append(";")
                .append("filename*=")
                .append("utf-8''")
                .append(percentEncodedFileName);

        response.setHeader("Content-disposition", contentDispositionValue.toString());
        response.setHeader("download-filename", percentEncodedFileName);
    }

    /**
     * 百分号编码工具方法
     *
     * @param s 需要百分号编码的字符串
     * @return 百分号编码后的字符串
     */
    public static String percentEncode(String s) throws UnsupportedEncodingException {
        String encode = URLEncoder.encode(s, StandardCharsets.UTF_8.toString());
        return encode.replaceAll("\\+", "%20");
    }

    /**
     * MultipartFile装换成file
     */
    public static File MultipartFileToFile(MultipartFile multipartFile) throws Exception {
        File file = null;
        try {
            InputStream ins = null;
            ins = multipartFile.getInputStream();
            file = new File(multipartFile.getOriginalFilename());
            inputStreamToFile(ins, file);
            ins.close();
        } catch (Exception e) {
            log.error(e.toString());
            throw new Exception("MultipartFile转换file失败!");
        }
        return file;
    }

    public static void inputStreamToFile(InputStream ins, File file) throws Exception {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            log.error(e.toString());
            throw new Exception("InputStream转换file失败!");
        }
    }

    /**
     * 读取文件路径 filepath
     * 读取Excel中所有行和列，都用列表表示
     */
    public static List<List<Object>> readerExcelObj(String filepath) throws Exception {
        try {
            ExcelReader reader = ExcelUtil.getReader(filepath);
            List<List<Object>> readAll = reader.read();
            return readAll;
        } catch (Exception ex) {
            log.error(ex.getMessage());
            throw new Exception("读取文件失败，请稍后重试！");
        }
    }

    /**
     * 读取文件file
     * 读取Excel中所有行和列，都用列表表示
     */
    public static List<List<Object>> readerExcelObj(File file) throws Exception {
        try {
            ExcelReader reader = ExcelUtil.getReader(file);
            List<List<Object>> readAll = reader.read();
            // 读取出来的数据按照第一行个数补齐
            for (int i = 1; i < readAll.size(); i++) {
                int size = readAll.get(0).size(); // 第一行的个数
                int size2 = readAll.get(i).size(); // 第一行的个数
                List<Object> list = readAll.get(i);
                for (int k = 0; k < size - size2; k++) {
                    list.add(null);
                }
            }
            return readAll;
        } catch (Exception ex) {
            log.error(ex.getMessage());
            throw new Exception("读取文件失败，请稍后重试！");
        }
    }

    /**
     * 读取文件file
     * 读取Excel中所有行和列，都用列表表示
     */
    public static List<List<Object>> readerExcelObj(File file, int sheetIndex) throws Exception {
        try {
            ExcelReader reader = ExcelUtil.getReader(file, sheetIndex);
            List<List<Object>> readAll = reader.read();
            // 读取出来的数据按照第一行个数补齐
            for (int i = 1; i < readAll.size(); i++) {
                int size = readAll.get(0).size(); // 第一行的个数
                int size2 = readAll.get(i).size(); // 第一行的个数
                List<Object> list = readAll.get(i);
                for (int k = 0; k < size - size2; k++) {
                    list.add(null);
                }
            }
            return readAll;
        } catch (Exception ex) {
            log.error(ex.getMessage());
            throw new Exception("读取文件失败，请稍后重试！" + ex.getMessage());
        }
    }
    public static List<List<Object>> readerExcelObj(File file, int sheetIndex, int line) throws Exception {
        try {
            ExcelReader reader = ExcelUtil.getReader(file, sheetIndex);
            List<List<Object>> readAll = reader.read();
            // 读取出来的数据按照第一行个数补齐
            for (int i = line + 1; i < readAll.size(); i++) {
                int size = readAll.get(line).size(); // 第一行的个数
                int size2 = readAll.get(i).size(); // 第一行的个数
                List<Object> list = readAll.get(i);
                for (int k = 0; k < size - size2; k++) {
                    list.add(null);
                }
            }
            return readAll;
        } catch (Exception ex) {
            log.error(ex.getMessage());
            throw new Exception("读取文件失败，请稍后重试！" + ex.getMessage());
        }
    }

    /**
     * 读取文件file
     * 读取Excel中所有行和列，都用列表表示
     */
    public static List<List<Object>> readerExcelObj(File file, String sheetName) throws Exception {
        try {
            ExcelReader reader = ExcelUtil.getReader(file, sheetName);
            List<List<Object>> readAll = reader.read();
            // 读取出来的数据按照第一行个数补齐
            for (int i = 1; i < readAll.size(); i++) {
                int size = readAll.get(0).size(); // 第一行的个数
                int size2 = readAll.get(i).size(); // 第一行的个数
                List<Object> list = readAll.get(i);
                for (int k = 0; k < size - size2; k++) {
                    list.add(null);
                }
            }
            return readAll;
        } catch (Exception ex) {
            log.error(ex.getMessage());
            throw new Exception("读取文件失败，请稍后重试！" + ex.getMessage());
        }
    }

    /**
     * 读取文件file
     * 读取Excel中所有行和列，都用列表表示
     */
    public static List<List<Object>> readerExcelObj(File file, String sheetName, int line) throws Exception {
        try {
            ExcelReader reader = ExcelUtil.getReader(file, sheetName);
            List<List<Object>> readAll = reader.read();
            // 读取出来的数据按照第一行个数补齐
            for (int i = line + 1; i < readAll.size(); i++) {
                int size = readAll.get(line).size(); // 第一行的个数
                int size2 = readAll.get(i).size(); // 第一行的个数
                List<Object> list = readAll.get(i);
                for (int k = 0; k < size - size2; k++) {
                    list.add(null);
                }
            }
            return readAll;
        } catch (Exception ex) {
            log.error(ex.getMessage());
            throw new Exception("读取文件失败，请稍后重试！" + ex.getMessage());
        }
    }


    /**
     * 读取文件路径 filepath
     * 读取为Map列表，默认第一行为标题行，Map中的key为标题，value为标题对应的单元格值。
     */
    public static List<Map<String, Object>> readerExcelListMap(String filepath) throws Exception {
        try {
            ExcelReader reader = ExcelUtil.getReader(filepath);
            List<Map<String, Object>> readAll = reader.readAll();
            return readAll;
        } catch (Exception ex) {
            log.error(ex.getMessage());
            throw new Exception("读取文件失败，请稍后重试！");
        }
    }

    /**
     * 读取文件file
     * 读取为Map列表，默认第一行为标题行，Map中的key为标题，value为标题对应的单元格值。
     */
    public static List<Map<String, Object>> readerExcelListMap(File file) throws Exception {
        try {
            ExcelReader reader = ExcelUtil.getReader(file);
            List<Map<String, Object>> readAll = reader.readAll();
            return readAll;
        } catch (Exception ex) {
            log.error(ex.getMessage());
            throw new Exception("读取文件失败，请稍后重试！");
        }
    }

    /**
     * 读取文件filepath
     * 读取为Bean列表，Bean中的字段名为标题，字段值为标题对应的单元格值。
     *
     * @param filepath
     * @param tclass
     * @return
     * @throws Exception
     */
    public static List<Class> readerExcelBean(String filepath, Class tclass) throws Exception {
        try {
            ExcelReader reader = ExcelUtil.getReader(filepath);
            List<Class> all = reader.readAll(tclass);
            return all;
        } catch (Exception ex) {
            log.error(ex.getMessage());
            throw new Exception("读取文件失败，请稍后重试！");
        }
    }

    /**
     * 读取文件file
     * 读取为Bean列表，Bean中的字段名为标题，字段值为标题对应的单元格值。
     *
     * @param file
     * @param tclass
     * @return
     * @throws Exception
     */
    public static List<Class> readerExcelBean(File file, Class tclass) throws Exception {
        try {
            ExcelReader reader = ExcelUtil.getReader(file);
            List<Class> all = reader.readAll(tclass);
            return all;
        } catch (Exception ex) {
            log.error(ex.getMessage());
            throw new Exception("读取文件失败，请稍后重试！");
        }
    }

    public static List<Map<String, Object>> readerExcelListMapObject(File file, Class tclass) throws Exception {
        try {
            ExcelReader reader = ExcelUtil.getReader(file);
            List<Map<String, Object>> all = reader.readAll();
            return all;
        } catch (Exception ex) {
            log.error(ex.getMessage());
            throw new Exception("读取文件失败，请稍后重试！");
        }
    }

    public static List<List<Object>> readerExcelListObject(File file) throws Exception {
        try {
            ExcelReader reader = ExcelUtil.getReader(file);
            List<List<Object>> all = reader.read();
            return all;
        } catch (Exception ex) {
            log.error(ex.getMessage());
            throw new Exception("读取文件失败，请稍后重试！");
        }
    }

    public static String separator = "/";

    /**
     * 替换反斜杠为正斜杠
     *
     * @param str 要替换的字符串
     * @return {@link String}
     */
    public static String replaceSeparator(String str) {
        return StringUtils.isEmpty(str) ? "" : str.replaceAll("\\\\", separator);
    }

    /**
     * 获取当前文件的父路径
     *
     * @param filePath 文件路径
     * @return {@link String} 父级路径
     */
    public static String getParentPath(String filePath) {
        String s = replaceSeparator(filePath);
        return s.substring(0, s.lastIndexOf(separator));
    }
}
